layui.use(['form','tree','element','table','laytpl','treeGrid','layer','jquery'],function(){
    var form = layui.form,
        element = layui.element;
        $ = layui.$;
    var layer = parent.layer === undefined ? layui.layer : top.layer;
    var table = layui.table;
    var laytpl = layui.laytpl;
    var layedit = layui.layedit;


    //列表数据
    var option = {
        elem: '#tableList',
        url : '/agriecomProduce/list',
        cellMinWidth : 95,
        page : true,
        height : "full-125",
        limits : [10,15,20,25],
        limit : 15,
        id : "listTable",
        loading:true,
        cols : [[
            {type: "checkbox", fixed:"left", width:50},
            {field: 'produceId', title: '农产品Id', minWidth:200, align:'center'},
            {field: 'produceName', title: '农产品名称', minWidth:200, align:'center'},
            {field: 'produceBrief', title: '产品简介', align:'center'},
            {field: 'price', title: '产品价格',sort:true, minWidth:100, align:"center"},
            {field: 'unit', title: '价格单位', align:'center',minWidth:150},
            {field: 'merchantName', title: '农商名', align:'center',minWidth:150,templet:function (d){
                    var name = null;
                    $.ajax({
                        url:"/merchant/"+d.merchantId,
                        type:'GET',
                        async:false,
                        success:function (data){
                            name = data.merchantName;
                        }
                    });
                    return name;
                }},

            {field: 'producingArea', title: '产地来源', align:'center',minWidth:150},
            {field: 'stock', title: '库存', align:'center',minWidth:150},
            {field: 'sourceCode', title: '溯源码', align:'center',minWidth:150},
            {field: 'isHot', title: '是否热门', align:'center',minWidth:150, templet:function(d){
                    return d.isHot == "0" ? "否" : "是";
                }},
            {field: '', title: '更新时间', align:'center',minWidth:180,sort:true, templet:function(d){
                    //处理时间
                    var date = new Date(d.updateDate);
                    return date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();;
                }
            },
            {title: '操作', minWidth:175, templet:'#tableListBar',fixed:"right",align:"center"}
        ]]
    };

    //场景数据
    var height = $(document).height();
    $(".orgbox").css('height',(height - 40) + "px");
    $(window).on("resize",function () {
        $(".orgbox").css('height',(height - 40) + "px");
    });
    var treeData = {
        elem: '#tree' //指定元素
        , target: '_blank' //是否新选项卡打开（比如节点返回href才有效）
        , click: function (item) { //点击节点回调
            option.url = '/agriecomProduce/category';
            option.where = {categoryId: item.id};
            table.render(option);
        },
        nodes:null
    };
    $.get('/produceCategory/tree',function(data) {
        treeData.nodes = data.data;
        layui.tree(treeData);
    });

    //设备列表
    var tableIns = table.render(option);

    //搜索设备信息
    $(".search_btn").on("click",function(){
        var searchKey = $(".searchVal").val();
        if(searchKey != ''){
            option.url = '/agriecomProduce/produceList';
            option.method = 'post';
            option.where = {keyword: searchKey};
            table.render(option);
        }else{
            layer.msg("请输入搜索的内容");
        }
    });


    //添加设备
    $(".addBtn").click(function(){
        var index = layui.layer.open({
            title : "添加产品",
            type : 2,
            content : "produceAdd",
            area: ['100%',$(document).height() + 'px'],
            success : function(){
                //这里可以有写成功后的其他操作
                setTimeout(function(){
                    layui.layer.tips('点击此处返回设备列表', '.layui-layer-setwin .layui-layer-close', {
                        tips: 3
                    });
                },500)
            }
        });
        layui.layer.full(index);
        //改变窗口大小时，重置弹窗的宽高，防止超出可视区域（如F12调出debug的操作）
        $(window).on("resize",function(){
            layui.layer.full(index);
        });
    });



    //批量删除
    $(".delAll_btn").click(function(){
        var checkStatus = table.checkStatus('listTable'),//此处的id为table数据格式中的id
            data = checkStatus.data,
            idArr = [];
        if(data.length > 0) {
            for (var i in data) {
                idArr.push(data[i].produceId);
            }
            layer.confirm('确定删除选中的产品？', {icon: 3, title: '提示信息'}, function (index) {
                $.get("/agriecomProduce/batchDelete",{
                    ids : idArr  //将需要删除的newsId作为参数传入
                },function(data){
                    if (data.code == 200) {
                        layer.msg("删除成功！");
                    } else {
                        layer.msg("删除失败，请重试！");
                    }
                    tableIns.reload();
                    layer.close(index);
                })

            })
        }else{
            layer.msg("请选择需要删除的设备");
        }
    });

    //列表操作
    table.on('tool(tableList)', function(obj){
        var layEvent = obj.event,
            data = obj.data;
        if(layEvent === 'edit'){ //编辑
            var index = layui.layer.open({
                title : "修改产品信息",
                type : 2,
                content : "productEdit?id=" + data.produceId,
                area: ['100%',$(document).height() - 30 + 'px'],
                success : function(){
                    setTimeout(function(){
                        layui.layer.tips('点击此处返回列表', '.layui-layer-setwin .layui-layer-close', {
                            tips: 3
                        });
                    },500);
                }
            });
            layui.layer.full(index);
            //改变窗口大小时，重置弹窗的宽高，防止超出可视区域（如F12调出debug的操作）
            $(window).on("resize",function(){
                layui.layer.full(index);
            });
        }
        else if(layEvent === 'del'){ //删除
            layer.confirm('确定删除此产品吗？',{icon:3, title:'提示信息'},function(index){
                $.get("/agriecomProduce/delete?id=" + data.produceId,function(data){
                    if (data.code == 200) {
                        layer.msg("删除成功！");
                    } else {
                        layer.msg("删除失败，请重试！");
                    }
                    tableIns.reload();
                    layer.close(index);
                });
            });
        }
    });

});